package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class AccountReceiver {

    @Autowired
    private UserAccountService userAccountService;

    /**
     * 监听消息实现用户账户初始化
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_USER_REGISTER)
    public  void userRegister(ConsumerRecord<String, String> record) {
        //获取发送消息
        String userId = record.value();
        if (!StringUtils.isEmpty(userId)){
            //调用service方法
            userAccountService.initUserAccount(userId);
        }
    }

    /**
     * 扣减锁定金额
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_MINUS)
    public void minus(ConsumerRecord<String, String> record) {
        String orderNo = record.value();
        if (StringUtils.isEmpty(orderNo)) {
            return;
        }
        //扣减锁定金额
        userAccountService.minus(orderNo);
    }

    /**
     * 解锁锁定金额
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_UNLOCK)
    public void unlock(ConsumerRecord<String, String> record) {
        String orderNo = record.value();
        if (StringUtils.isEmpty(orderNo)) {
            return;
        }
        //  调用解除锁定
        userAccountService.unlock(orderNo);
    }
}
